import * as rq from 'request-promise';
import env from './../config/env';
import loginUtils from './../core/LoginUtils';
import * as moment from 'moment';
import logger from '../lib/Log4js';

export class RkService {

    /**
     * b2b
     * 采购配送单查询
     * pda扫描配送单 只生成配送单号 deliveryId :S012496
     * 采购配送单查询
     * 采购订单配送到货后扫描入库时，根据采购订单配送单号查询配送单详情
     * getSupDeliveryInfo =>getPurchaseDeliveryInfo
     */
    async getSupDeliveryInfo(res, authorization) {
        
        let checkNum: number = await loginUtils.checkUser(authorization);
        if (checkNum == 101) {
            return { code: checkNum };
        }

        let user_info = loginUtils.decode(authorization);
        let opeUser: string = user_info.username;
        console.log('request:', res);

        //防止SQL注入攻击
        var reg = /^[a-zA-Z0-9]{1,20}$/;
        if(!reg.test(res.deliveryId)) {
            return { 
                "responseMessage": "fail",
                "errorMessage": "输入的格式不正确",
                "code": 0
            };
        }

        let json = await rq.post(`${env.b2bUrl}/portal/control/wsif/getPurchaseDeliveryInfo`,
            {
                form: { 'login.username': env.loginUsername, 'login.password': env.loginPwd, 'deliveryId': res.deliveryId, opeUser: opeUser },
                json: true
            })

            console.log(json,'jsonjsonjsonjsonjson')

        if (json.responseMessage.includes('success')) {

            //采购订单时对应的ERP采购订单号
            let originalOrderId: string = json.baseInfo.originalOrderId;
            //客户公司编码 =>公司名称
            let supplierName: string = json.baseInfo.supplierName;
            //入库日期
            let date: string = moment().format('YYYY-MM-DD');
            //发货日期
            let deliveryTime: string = moment(json.baseInfo.deliveryTime).format('YYYY-MM-DD');
            //配送单号 => 平台送货单号(扫描得到)
            let deliveryId: string = json.baseInfo.deliveryId;
            //状态
            let receiveStatus: string = json.baseInfo.receiveStatus;
            //CR单号
            let erpInBillCode: string = json.baseInfo.erpInBillCode;

            //商品信息 => List<Map>
            let productInfo = json.productInfo;
            let product_list: any = [];
            let invcodeList :any = [];//商品编码集合
            productInfo.map((item, i) => {
                product_list[i] = {
                    orderItemSeqId: item.orderItemSeqId,//发货订单项行号
                    productCode: item.productCode,//商品编码
                    productName: item.productName,//商品名称
                    unit: item.unit,//计量单位
                    quantity: (item.quantity - 0).toFixed(2),//配送数量
                    scanNum: (item.quantity - 0).toFixed(2),//打印数量
                    cscode : ''
                };
                invcodeList.push(item.productCode);
            });

            console.log('invcodeList__________________',invcodeList);
            // QueryStoreLocation
            let location = await rq.post(`${env.testUrl}/service/QueryStoreLocation`,
            {
                body: { storcode: res.storcode, invcodes : invcodeList },
                json: true
            })

            console.log('loca__________________',location);
            console.log('product_list__________________',product_list);
            if(location.rtcode == 1 && location.cargdoc.length > 0){
                for (let i = 0; i < product_list.length; i++) {
                    let item = product_list[i];
                    let productCode = item.productCode;
                    for (let j = 0; j < location.cargdoc.length; j++) {
                        let item2 = location.cargdoc[j];
                        if(item2.invcode == productCode){
                            item.cscode = item2.cscode;
                        }
                    }
                }
            }

            return {
                code: 1,
                originalOrderId: originalOrderId,
                supplierName: supplierName,
                date: date,
                deliveryTime: deliveryTime,
                deliveryId: deliveryId,
                receiveStatus: receiveStatus,
                product_list: product_list,
                erpInBillCode: erpInBillCode
            };

        }

        //失败返回
        json.code = 0;

        return json;
    }


    /**
     * 采购入库接口
     * 参数 
     * ERP 采购订单号 :purchasebillcode
     * 平台送货单号 : deliverybillcode
     * 单据明细: details  > List<Map>
     * 订单id : corderbid
     * 配送数量 :nnum     > number
     */
    async acceptSupDelivery(res, authorization) {
        let facilityId  = res.storcode;
        let checkNum: number = await loginUtils.checkUser(authorization);
        if (checkNum == 101) {
            return { code: checkNum };
        }
        let user_info = loginUtils.decode(authorization);
        logger.infoLogger().info('仓库编码————————let facilityId  = res.storcode;' + facilityId );

        //平台送货单号
        let deliveryId: string = res.data.deliveryId;
        logger.infoLogger().info('平台送货单号deliveryId___________' + deliveryId);
        logger.infoLogger().info('login.username_________' + env.loginUsername);
        logger.infoLogger().info('opeUser_________' + user_info.username );

        /**
         * 采购配送单确认收货
         * 返回值:
         * {
         *  "responseMessage": "success",
         *  "errorMessage": ""
         *  }
         *   acceptSupDelivery 改成 acceptPurchaseDelivery
         */
        let result :any = {};
        try {
            result = await rq.post(`${env.b2bUrl}/portal/control/wsif/acceptPurchaseDelivery`,
                {
                    form: { 'login.username': env.loginUsername, 'login.password': env.loginPwd, 'deliveryId': deliveryId,facilityId:facilityId, 'opeUser': user_info.username },
                    json: true
                });
        } catch (error) {
            logger.infoLogger().info('error======================================' + JSON.stringify(error));
        }
        
        logger.infoLogger().info('result_info_____________________________' + JSON.stringify(result) );

        
        if (result.responseMessage !='success' )
            return { code: 0, msg: result.errorMessage };
        result.code = 1;
        return result;
    }

}


let rkService = new RkService();
export default rkService;